﻿/*
 * zhoujiliang02 创建于 2021/8/17 9:56:16
 */

using Newtonsoft.Json;
using Pipelines.Sockets.Unofficial.Arenas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Domain.Repository.Interface.Sys;
using VisionCloud.Utility;

namespace VisionCloud.Service.Ms
{
    /// <summary>
    /// 项目编辑日志收集。只在发布项目时收集最终发布的差异日志，变更者为发布者。
    /// </summary>
    public class MsProjectEditLogService
    {
        public IMsProjectEditLogRepository MsProjectEditLogRepository { set; get; }
        public IMsHouseMapRepository MsHouseMapRepository { set; get; }
        public IMsProjectStandardRepository MsProjectStandardRepository { set; get; }
        public ISysUserRepository SysUserRepository { set; get; }

        public async Task AddChangeProjectUsersLog(IEnumerable<Guid> oldUserIds, IEnumerable<Guid> newUserIds, List<SysUser> userInfos, MsProject project, Guid createId)
        {
            string changeLog = string.Empty;
            if (oldUserIds != null && oldUserIds.Count() > 0)
            {
                var users = userInfos.Where(x => oldUserIds.Contains(x.YunUserGuid)).Select(u => u.Name).ToList();
                changeLog += $"项目新增分配给：{string.Join(",", users)}";
            }
            if (newUserIds != null && newUserIds.Count() > 0)
            {
                changeLog += string.IsNullOrEmpty(changeLog) ? string.Empty : "，";
                var users = userInfos.Where(x => newUserIds.Contains(x.YunUserGuid)).Select(u => u.Name).ToList();
                changeLog += $"项目取消分配给：{string.Join(",", users)}";
            }
            if (!string.IsNullOrEmpty(changeLog))
            {
                MsProjectEditLogRepository.Add(new MsProjectEditLog
                {
                    EditLogId = Guid.NewGuid(),
                    CreatedBy = createId,
                    CreatedDate = DateTime.Now,
                    EditType = MsProjectEditTypeEnum.分配项目.ToString(),
                    ProjectId = project.ProjectId,
                    ProjectName = project.Name,
                    IsDeleted = false,
                    IsPublished = true,
                    ChangeLog = changeLog
                });
            }
        }

        /// <summary>
        /// 发布时写入发布日志:楼层、户型、测量点
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        public async Task WriteProjectPublishLog(MsProject project)
        {
            if (project == null || project.PubliceDate == null) return;
            var userInfo = OperatorProvider.Get();

            #region 项目楼栋变更

            // 目前只能变更楼层，只校验楼层变化就行。
            var detailInfoList = JsonConvert.DeserializeObject<List<Detail>>(project.Details);
            if (detailInfoList != null)
            {
                var unPublishedList = detailInfoList.GetRange(project.PubliceDetailsCount, detailInfoList.Count() - project.PubliceDetailsCount);
                if (unPublishedList.Count > 0)
                {
                    var log = "楼栋新增：";
                    unPublishedList.ForEach(x =>
                    {
                        log += $"{x.Building}栋 ";
                    });
                    MsProjectEditLog projectLog = new MsProjectEditLog
                    {
                        EditLogId = Guid.NewGuid(),
                        CreatedBy = userInfo.YunUserGuid,
                        CreatedDate = DateTime.Now,
                        EditType = MsProjectEditTypeEnum.项目信息.ToString(),
                        ProjectId = project.ProjectId,
                        ProjectName = project.Name,
                        IsDeleted = false,
                        IsPublished = true,
                        ChangeLog = log
                    };
                    MsProjectEditLogRepository.Add(projectLog);
                }
            }

            #endregion 项目楼栋变更

            #region 户型图变更

            // 取未发布的户型,记录变更日志
            var publicDate = project.PubliceDate == null ? DateTime.MinValue : project.PubliceDate;
            var houseList = await MsHouseMapRepository.WhereAsync(x => x.ProjectId == project.ProjectId && x.IsDeleted == false && (x.CreatedDate > publicDate || x.LastUpdatedDate > publicDate)).ConfigureAwait(false);
            if (houseList.Count > 0)
            {
                var log = "";
                houseList.ForEach(x =>
                {

                    if (x.CreatedDate > publicDate)
                        log += $"新增户型图：{x.Name} ";
                    else
                        log += $"修改户型图：{x.Name} ";
                });
                MsProjectEditLog houseLog = new MsProjectEditLog
                {
                    EditLogId = Guid.NewGuid(),
                    CreatedBy = userInfo.YunUserGuid,
                    CreatedDate = DateTime.Now,
                    EditType = MsProjectEditTypeEnum.户型图.ToString(),
                    ProjectId = project.ProjectId,
                    ProjectName = project.Name,
                    IsDeleted = false,
                    IsPublished = true,
                    ChangeLog = log
                };
                MsProjectEditLogRepository.Add(houseLog);
            }

            #endregion 户型图变更

            #region 标准库变更---把已经记录的数据改为已发布

            var updateList = await MsProjectEditLogRepository.WhereAsync(x => x.ProjectId == project.ProjectId && x.IsDeleted == false && x.IsPublished == false).ConfigureAwait(false);
            updateList.ForEach(x =>
            {
                x.IsPublished = true;
                x.LastUpdatedBy = userInfo.YunUserGuid;
                x.LastUpdatedDate = DateTime.Now;
                MsProjectEditLogRepository.Update(x, y => new { y.IsPublished, y.LastUpdatedBy, y.LastUpdatedDate });
            });

            #endregion 标准库变更---把已经记录的数据改为已发布
        }

        /// <summary>
        /// 根据项目id获取所有日志
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetLogsByProjectId(string projectIdStr)
        {
            if (string.IsNullOrWhiteSpace(projectIdStr))
                throw new OperationException("YB0008".SLocalize());
            if (projectIdStr.Length != 36)
                throw new OperationException("YB0060".SLocalize());
            var projectId = Guid.Parse(projectIdStr); ;
            var query = await MsProjectEditLogRepository.WhereAsync(x => x.ProjectId == projectId && x.IsPublished);
            var logs = query.Select(x => new MsProjectEditLogDto
            {
                EditLogId = x.EditLogId,
                ProjectId = x.ProjectId,
                ProjectName = x.ProjectName,
                EditType = x.EditType,
                ChangeLog = x.ChangeLog,
                // LastUpdatedDate字段不为空
                CreateDate = x.LastUpdatedDate.ToString("yyyy-MM-dd HH:mm"),
                CreateTime = x.LastUpdatedDate,
                CreateBy = x.CreatedBy,
            }).OrderByDescending(x => x.CreateTime).ToList();
            if (logs.Count > 0)
            {
                var users = SysUserRepository.Where(x => logs.Select(y => y.CreateBy).Contains(x.YunUserGuid)).ToList();
                logs.ForEach(l =>
                {
                    var user = users.FirstOrDefault(x => x.YunUserGuid == l.CreateBy);
                    l.CreateName = user == null ? "" : user.Name;
                });
            }
            return new ApiResult
            {
                Code = AjaxCode.Success,
                Result = logs
            };
        }
    }
}